package mysql

import (
	"context"
	"data-transfer/domain"
	"data-transfer/global"
	"data-transfer/transfer"
	"data-transfer/utils"
	"fmt"
	"go.uber.org/zap"
	"strconv"
	"strings"
)

//GetAllAnnouncement 根据股票信息 获取所有公告信息
func (mdb *db) GetAllAnnouncement(ctx context.Context, basicInfos []*domain.TQ_SK_BASICINFO) ([]*domain.ANNOUNCEMENT, error) {
	var rows []*domain.ANNOUNCEMENT

	for _, o := range basicInfos {
		// var tempRows []*domain.ANNOUNCEMENT // //每一个compCode对应一个结果集

		symbol := o.Symbol //证券代码
		compCode := o.Compcode
		exchange := o.Exchange

		annoucemts, err := mdb.GetTqSkAnnouncemtByCompCode(ctx, compCode)
		if err != nil {
			global.LOG.Error("获取 公告 数据出错:", zap.Any("err", err))
			return nil, err
		}

		for _, v := range annoucemts {
			r := new(domain.ANNOUNCEMENT)
			r.Symbol = symbol
			r.Exchange = transfer.TransferExchane(exchange) //市场代码
			r.Compcode = v.Compcode                         //机构代码
			r.Declaredate = utils.DateParse(v.Declaredate)  //公告日期
			r.Anntitle = v.Anntitle                         //公告标题
			//r.Anntext = v.Anntext                         //全文
			r.Anntext = ""                  //全文内容设置为空
			r.Announcemtid = v.Announcemtid //公告ID
			r.Shares = 0                    //分享数，默认初始化为0
			r.Views = 0                     //阅读数，默认初始化为0
			r.Collections = 0               //收藏数，默认初始化为0

			fileLink := ""
			anntFile, errf := mdb.GetTqQaAnntFileByAnnouncemtId(ctx, v.Announcemtid)
			if errf != nil {
				global.LOG.Error("获取 公告目录文件 数据出错:", zap.Any("err", errf))
			}
			if anntFile != nil && len(anntFile.Filelink) > 0 {
				fileLink = anntFile.Filelink
			}
			//设置fileLink  strings.ReplaceAll(path, string(Separator), "/")
			//r.Filelink = filepath.ToSlash(fileLink)
			if len(fileLink) > 0 { //存在文件链接地址的才能加入结果集
				r.Filelink = strings.ReplaceAll(fileLink, "\\", "/")
				rows = append(rows, r)
			}

		}

		//累加每一个compCode的结果集
		//rows = append(rows, tempRows...)
	}
	return rows, nil
}

//GetTqSkAnnouncemtByCompCode 根据compCode 取得公告信息(有效且已发布的),一年之内的数据
func (mdb *db) GetTqSkAnnouncemtByCompCode(ctx context.Context, compCode string) ([]*domain.TQ_SK_ANNOUNCEMT, error) {
	var results []*domain.TQ_SK_ANNOUNCEMT
	err := mdb.db.NewSession().Where("DECLAREDATE > DATE_SUB(CURDATE(), INTERVAL 1 YEAR) and ISVALID=? and STATUS = ? and COMPCODE = ?", 1, "2", compCode).Desc("DECLAREDATE").Find(&results) //查询有效和已发布的
	return results, err
}

//GetTqQaAnntFileByAnnouncemtId 根据公告ID获取PDF文件的路径相对目录
func (mdb *db) GetTqQaAnntFileByAnnouncemtId(ctx context.Context, announcemtId int) (*domain.TQ_OA_ANNTFILE_DLFC, error) {
	result := new(domain.TQ_OA_ANNTFILE_DLFC)
	_, err := mdb.db.NewSession().Where("RELATABLE = ? and RELAID = ?", transfer.ANNTFILE_TQ_SK_ANNOUNCEMT, announcemtId).Get(result)
	return result, err
}

// GetAllAnnouncement4Fix 获取时间间隔范围内的公告信息,用于补充数据
func (mdb *db) GetAllAnnouncement4Fix(ctx context.Context, startDate string, endDate string) ([]*domain.ANNOUNCEMENT, error) {
	var rows []*domain.ANNOUNCEMENT

	// 查询指定录入日期范围的公告数据
	sql := "select * from TQ_SK_ANNOUNCEMT where UNIX_TIMESTAMP(ENTRYDATE) between UNIX_TIMESTAMP('" + startDate + "') and UNIX_TIMESTAMP('" + endDate + "') and STATUS = '2' "
	datas, err := mdb.db.Query(sql)
	if err != nil {
		global.LOG.Error("查询公告【TQ_SK_ANNOUNCEMT】信息出错:", zap.Any("err", err))
		return nil, err
	}

	//获取所有证券信息，用于获取symbol和exchange
	skBasicInfos, err := mdb.GetAllTqSkBasicInfo(ctx)
	if err != nil {
		global.LOG.Error("查询所有【TQ_SK_BASICINFO】信息出错:", zap.Any("err", err))
		return nil, err
	}

	for _, d := range datas {
		r := new(domain.ANNOUNCEMENT)

		compCode := fmt.Sprintf("%s", d["COMPCODE"])
		r.Compcode = compCode //机构代码

		basicInfo := getSkBasicInfoByCompCode(skBasicInfos, compCode)
		if basicInfo != nil {

			announcemtID := fmt.Sprintf("%s", d["ANNOUNCEMTID"])
			id, _ := strconv.Atoi(announcemtID)
			r.Announcemtid = id //公告ID

			declareDateStr := fmt.Sprintf("%s", d["DECLAREDATE"])
			r.Declaredate = utils.DateParse(declareDateStr) //公告日期

			anntTitle := fmt.Sprintf("%s", d["ANNTITLE"])
			r.Anntitle = anntTitle //公告标题
			r.Anntext = ""         //全文内容设置为空

			symbol := basicInfo.Symbol
			r.Symbol = symbol
			r.Exchange = transfer.TransferExchane(basicInfo.Exchange) //市场代码

			r.Shares = 0      //分享数，默认初始化为0
			r.Views = 0       //阅读数，默认初始化为0
			r.Collections = 0 //收藏数，默认初始化为0

			fileLink := ""
			anntFile, errf := mdb.GetTqQaAnntFileByAnnouncemtId(ctx, id)
			if errf != nil {
				global.LOG.Error("获取 公告目录文件 数据出错:", zap.Any("err", errf))
			}
			if anntFile != nil && len(anntFile.Filelink) > 0 {
				fileLink = anntFile.Filelink
			}
			//设置fileLink  strings.ReplaceAll(path, string(Separator), "/")
			//r.Filelink = filepath.ToSlash(fileLink)
			if len(fileLink) > 0 { //存在文件链接地址的才能加入结果集
				r.Filelink = strings.ReplaceAll(fileLink, "\\", "/")
				rows = append(rows, r)
			}

		}

	}

	return rows, err
}

func getSkBasicInfoByCompCode(infos []*domain.TQ_SK_BASICINFO, compCode string) *domain.TQ_SK_BASICINFO {
	for _, o := range infos {
		if o.Compcode == compCode {
			return o
		}
	}
	return nil
}

func getSkBasicInfoBySymbol(infos []*domain.TQ_SK_BASICINFO, symbol string) *domain.TQ_SK_BASICINFO {
	for _, o := range infos {
		if o.Symbol == symbol {
			return o
		}
	}
	return nil
}
